<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>Reset Password - TBPLAS</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="shortcut icon" href="./img/logo.png" type="image/x-icon">
  <link rel="stylesheet" href="./css/element.css">
  <link rel="stylesheet" href="./css/index.css">
  <script src="./js/vue.js"></script>
  <script src="./js/axios.js"></script>
  <script src="./js/element.js"></script>
  <script src="./router.js"></script>
</head>

<body>
  <div id="app">
    <div class="container">
      <div class="form-header">
        <p>Enter your email to reset your password.</p>
      </div>

      <div class="form-content" style="padding-top: 15px;">
        <el-form ref="form" :model="form">
          <el-form-item prop="email" label="E-mail"
            :rules="[{ required: true, message: 'Please enter email', trigger: 'blur' }, { type: 'email', message: 'Invalid email', trigger: ['blur', 'change'] }]">
            <el-input v-model="form.email" placeholder="xxx@yyy.com" clearable>
              <el-button slot="append" :disabled="isCountingDown || isSending || !form.email" @click="sendCode">
                {{ isCountingDown ? countdown + 's' : 'Get Code' }}
              </el-button>
            </el-input>
          </el-form-item>

          <el-form-item prop="code" label="Verification Code"
            :rules="[{ required: true, message: 'Enter the code', trigger: 'blur' }]">
            <el-input v-model="form.code" placeholder="Enter code"></el-input>
          </el-form-item>

          <el-form-item prop="newPassword" label="New Password"
            :rules="[{ required: true, message: 'Enter new password', trigger: 'blur' }]">
            <el-input type="password" v-model="form.newPassword" placeholder="New password"></el-input>
          </el-form-item>

          <div class="submit-area">
            <button class="submit-btn" @click.prevent="resetPassword" :disabled="isSubmitting">
              {{ isSubmitting ? 'Resetting...' : 'Reset Password' }}
            </button>
          </div>
        </el-form>
      </div>
    </div>
  </div>

  <script>
    new Vue({
      el: '#app',
      data() {
        return {
          form: {
            email: '',
            code: '',
            newPassword: ''
          },
          isSubmitting: false,
          isCountingDown: false,
          countdown: 60,
          countdownTimer: null,
          isSending: false
        };
      },
      methods: {
        sendCode() {
          if (!this.form.email || !isValidEmail(this.form.email)) return;
          this.isSending = true;
          axios.post(`${api}/sendEmailCode`, { email: this.form.email })
            .then(() => {
              this.$notify({ title: 'Success', message: 'Verification code sent', type: 'success' });
              this.startCountdown();
            })
            .catch((error) => {
              this.$notify.error({ title: 'Error', message: 'Failed to send code' });
              errorLog('forgot-password', error)
            })
            .finally(() => this.isSending = false);
        },
        startCountdown() {
          this.isCountingDown = true;
          this.countdown = 60;
          this.countdownTimer = setInterval(() => {
            this.countdown--;
            if (this.countdown <= 0) {
              clearInterval(this.countdownTimer);
              this.isCountingDown = false;
            }
          }, 1000);
        },
        resetPassword() {
          this.$refs.form.validate((valid) => {
            if (!valid) return;
            if (!/^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d\W_]{6,}$/.test(this.form.newPassword)) {
              this.$notify.error({
                title: 'fail to submit',
                message: 'The password must be at least 6 characters long and contain both letters and numbers.',
                duration: 2000
              });
              return false;
            }
            this.isSubmitting = true;
            axios.post(`${api}/resetPassword`, this.form)
              .then((response) => {
                if (response.data.code == 200) {
                  this.$notify({
                    title: 'success',
                    message: 'submit successfully',
                    type: 'success'
                  });
                  setTimeout(() => {
                    window.location.href = './login.html';
                  }, 1000);
                } else {
                  this.$notify.error({
                    title: 'fail',
                    message: response.data.msg,
                    duration: 2000
                  });
                  errorLog('forgot-password', response.data.msg)
                }
              })
              .catch((error) => {
                this.$notify.error({ title: 'Error', message: 'Reset failed' });
                errorLog('forgot-password', error)
              })
              .finally(() => this.isSubmitting = false);
          });
        }
      }
    });
  </script>
</body>

</html>